package com.liuzhilin.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liuzhilin.domain.Article;
import com.liuzhilin.service.UserService;
import com.liuzhilin.util.Response;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/userArticleSelect")
public class UserArticleSelect extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应类型为 JSON
        Response.setCorsHeaders(response);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        // 从前端请求中获取搜索参数
        String searchQuery = request.getParameter("query");
        String Category = request.getParameter("category");
        System.out.println("searchQuery: " + searchQuery+"Category: "+Category);

        // 调用业务逻辑层，获取搜索结果
        List<Article> articles = UserService.getSelectArticles(searchQuery,Category);

        // 将结果转换为 JSON 并返回
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.writeValue(out, articles);
    }
    @Override
    public void doOptions(HttpServletRequest request, HttpServletResponse response) {
        Response.setCorsHeaders(response);
        response.setStatus(HttpServletResponse.SC_OK);
    }
}
